/**
 * 登录组件
 * Login Component
 */

class LoginComponent {
  constructor() {
    this.form = document.getElementById('login-form');
    this.emailInput = document.getElementById('email');
    this.passwordInput = document.getElementById('password');
    this.togglePasswordBtn = document.getElementById('toggle-password');
    this.rememberMeCheckbox = document.getElementById('remember-me');
    this.loginBtn = document.getElementById('login-btn');
    this.loginBtnText = document.getElementById('login-btn-text');
    this.loginBtnLoading = document.getElementById('login-btn-loading');
    this.formError = document.getElementById('form-error');
    this.formErrorMessage = document.getElementById('form-error-message');
    this.emailError = document.getElementById('email-error');
    this.passwordError = document.getElementById('password-error');
    this.systemStatus = document.getElementById('system-status');
    
    // 登录尝试计数
    this.loginAttempts = 0;
    this.maxAttempts = 5;
    this.lockoutTime = 15 * 60 * 1000; // 15分钟
    
    this.init();
  }

  init() {
    this.bindEvents();
    this.loadRememberedEmail();
    this.checkSystemStatus();
    this.setupFormValidation();
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 表单提交事件
    if (this.form) {
      this.form.addEventListener('submit', (e) => {
        e.preventDefault();
        this.handleLogin();
      });
    }

    // 密码显示/隐藏切换
    if (this.togglePasswordBtn) {
      this.togglePasswordBtn.addEventListener('click', () => {
        this.togglePasswordVisibility();
      });
    }

    // 输入框事件
    if (this.emailInput) {
      this.emailInput.addEventListener('input', () => {
        this.clearFieldError('email');
        this.updateFormState();
      });
      
      this.emailInput.addEventListener('blur', () => {
        this.validateEmail();
      });
      
      this.emailInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          this.passwordInput.focus();
        }
      });
    }

    if (this.passwordInput) {
      this.passwordInput.addEventListener('input', () => {
        this.clearFieldError('password');
        this.updateFormState();
      });
      
      this.passwordInput.addEventListener('blur', () => {
        this.validatePassword();
      });
      
      this.passwordInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          this.handleLogin();
        }
      });
    }

    // 记住我选项变化
    if (this.rememberMeCheckbox) {
      this.rememberMeCheckbox.addEventListener('change', () => {
        this.updateFormState();
      });
    }

    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
      // Ctrl/Cmd + Enter 快速登录
      if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        this.handleLogin();
      }
      
      // Esc 清除错误信息
      if (e.key === 'Escape') {
        this.hideFormError();
      }
    });
  }

  /**
   * 处理登录
   */
  async handleLogin() {
    // 检查是否被锁定
    if (this.isAccountLocked()) {
      this.showFormError('账户已被临时锁定，请稍后再试 / Account temporarily locked, please try again later');
      return;
    }

    // 验证表单
    if (!this.validateForm()) {
      return;
    }

    const email = this.emailInput.value.trim();
    const password = this.passwordInput.value;
    const rememberMe = this.rememberMeCheckbox.checked;

    try {
      this.setLoading(true);
      this.hideFormError();

      // 调用认证管理器登录
      const response = await auth.login(email, password, rememberMe);

      // 登录成功
      this.loginAttempts = 0; // 重置尝试次数
      localStorage.removeItem('login_lockout');

      // 保存邮箱（如果选择了记住我）
      if (rememberMe) {
        localStorage.setItem('remembered_email', email);
      } else {
        localStorage.removeItem('remembered_email');
      }

      // 显示成功消息
      notification.success('登录成功！正在跳转... / Login successful! Redirecting...');

      // 立即跳转到仪表盘
      auth.redirectToDashboard();
      
      // 初始化仪表盘
      if (typeof Dashboard !== 'undefined') {
        window.dashboard = new Dashboard();
      }

    } catch (error) {
      console.error('登录失败:', error);
      
      // 增加失败尝试次数
      this.loginAttempts++;
      
      // 检查是否需要锁定
      if (this.loginAttempts >= this.maxAttempts) {
        this.lockAccount();
        this.showFormError(`登录失败次数过多，账户已被锁定${this.lockoutTime / 60000}分钟 / Too many failed attempts, account locked for ${this.lockoutTime / 60000} minutes`);
      } else {
        const remainingAttempts = this.maxAttempts - this.loginAttempts;
        let errorMessage = error.message || '登录失败，请检查邮箱和密码 / Login failed, please check email and password';
        
        if (remainingAttempts > 0) {
          errorMessage += ` (剩余尝试次数: ${remainingAttempts} / Remaining attempts: ${remainingAttempts})`;
        }
        
        this.showFormError(errorMessage);
      }

      // 清空密码输入框
      this.passwordInput.value = '';
      this.passwordInput.focus();

    } finally {
      this.setLoading(false);
    }
  }

  /**
   * 切换密码可见性
   */
  togglePasswordVisibility() {
    const isPassword = this.passwordInput.type === 'password';
    this.passwordInput.type = isPassword ? 'text' : 'password';
    
    const icon = this.togglePasswordBtn.querySelector('i');
    icon.className = isPassword ? 'fa fa-eye-slash' : 'fa fa-eye';
  }

  /**
   * 验证表单
   */
  validateForm() {
    let isValid = true;

    // 验证邮箱
    if (!this.validateEmail()) {
      isValid = false;
    }

    // 验证密码
    if (!this.validatePassword()) {
      isValid = false;
    }

    return isValid;
  }

  /**
   * 验证邮箱
   */
  validateEmail() {
    const email = this.emailInput.value.trim();
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (!email) {
      this.setFieldError('email', '请输入邮箱地址 / Please enter email address');
      return false;
    }

    if (!emailRegex.test(email)) {
      this.setFieldError('email', '请输入有效的邮箱地址 / Please enter a valid email address');
      return false;
    }

    this.clearFieldError('email');
    this.setFieldSuccess('email');
    return true;
  }

  /**
   * 验证密码
   */
  validatePassword() {
    const password = this.passwordInput.value;

    if (!password) {
      this.setFieldError('password', '请输入密码 / Please enter password');
      return false;
    }

    if (password.length < 6) {
      this.setFieldError('password', '密码至少6位字符 / Password must be at least 6 characters');
      return false;
    }

    this.clearFieldError('password');
    this.setFieldSuccess('password');
    return true;
  }

  /**
   * 设置字段错误
   */
  setFieldError(fieldName, message) {
    const input = fieldName === 'email' ? this.emailInput : this.passwordInput;
    const errorDiv = fieldName === 'email' ? this.emailError : this.passwordError;

    if (input && errorDiv) {
      input.classList.add('input-error');
      input.classList.remove('input-success');
      errorDiv.textContent = message;
      errorDiv.classList.remove('hidden');
      errorDiv.classList.add('fade-in');
    }
  }

  /**
   * 清除字段错误
   */
  clearFieldError(fieldName) {
    const input = fieldName === 'email' ? this.emailInput : this.passwordInput;
    const errorDiv = fieldName === 'email' ? this.emailError : this.passwordError;

    if (input && errorDiv) {
      input.classList.remove('input-error');
      errorDiv.classList.add('hidden');
      errorDiv.classList.remove('fade-in');
    }
  }

  /**
   * 设置字段成功状态
   */
  setFieldSuccess(fieldName) {
    const input = fieldName === 'email' ? this.emailInput : this.passwordInput;
    
    if (input) {
      input.classList.add('input-success');
      input.classList.remove('input-error');
    }
  }

  /**
   * 设置加载状态
   */
  setLoading(loading) {
    if (loading) {
      this.loginBtn.disabled = true;
      this.loginBtnText.classList.add('hidden');
      this.loginBtnLoading.classList.remove('hidden');
      
      // 禁用表单输入
      this.emailInput.disabled = true;
      this.passwordInput.disabled = true;
      this.rememberMeCheckbox.disabled = true;
      this.togglePasswordBtn.disabled = true;
    } else {
      this.loginBtn.disabled = false;
      this.loginBtnText.classList.remove('hidden');
      this.loginBtnLoading.classList.add('hidden');
      
      // 启用表单输入
      this.emailInput.disabled = false;
      this.passwordInput.disabled = false;
      this.rememberMeCheckbox.disabled = false;
      this.togglePasswordBtn.disabled = false;
    }
  }

  /**
   * 加载记住的邮箱
   */
  loadRememberedEmail() {
    const rememberedEmail = localStorage.getItem('remembered_email');
    if (rememberedEmail && this.emailInput) {
      this.emailInput.value = rememberedEmail;
      this.rememberMeCheckbox.checked = true;
      
      // 自动聚焦到密码输入框
      if (this.passwordInput) {
        this.passwordInput.focus();
      }
    }
  }

  /**
   * 显示表单错误
   */
  showFormError(message) {
    if (this.formError && this.formErrorMessage) {
      this.formErrorMessage.textContent = message;
      this.formError.classList.remove('hidden');
      this.formError.classList.add('slide-up');
    }
  }

  /**
   * 隐藏表单错误
   */
  hideFormError() {
    if (this.formError) {
      this.formError.classList.add('hidden');
      this.formError.classList.remove('slide-up');
    }
  }

  /**
   * 更新表单状态
   */
  updateFormState() {
    const email = this.emailInput.value.trim();
    const password = this.passwordInput.value;
    
    // 检查表单是否可以提交
    const canSubmit = email.length > 0 && password.length > 0 && !this.isAccountLocked();
    
    if (this.loginBtn) {
      this.loginBtn.disabled = !canSubmit;
    }
  }

  /**
   * 设置表单验证
   */
  setupFormValidation() {
    // 初始状态下禁用提交按钮
    this.updateFormState();
  }

  /**
   * 检查系统状态
   */
  async checkSystemStatus() {
    try {
      const response = await api.get('/auth/status');
      if (response.success) {
        this.setSystemStatus('online');
      }
    } catch (error) {
      this.setSystemStatus('offline');
    }
  }

  /**
   * 设置系统状态
   */
  setSystemStatus(status) {
    if (this.systemStatus) {
      if (status === 'online') {
        this.systemStatus.className = 'w-2 h-2 bg-success rounded-full pulse-slow';
        this.systemStatus.parentElement.querySelector('span').textContent = '系统正常 / System OK';
      } else {
        this.systemStatus.className = 'w-2 h-2 bg-red-500 rounded-full';
        this.systemStatus.parentElement.querySelector('span').textContent = '系统异常 / System Error';
      }
    }
  }

  /**
   * 检查账户是否被锁定
   */
  isAccountLocked() {
    const lockoutData = localStorage.getItem('login_lockout');
    if (!lockoutData) return false;

    const { timestamp } = JSON.parse(lockoutData);
    const now = Date.now();
    
    if (now - timestamp > this.lockoutTime) {
      localStorage.removeItem('login_lockout');
      this.loginAttempts = 0;
      return false;
    }
    
    return true;
  }

  /**
   * 锁定账户
   */
  lockAccount() {
    const lockoutData = {
      timestamp: Date.now(),
      attempts: this.loginAttempts
    };
    localStorage.setItem('login_lockout', JSON.stringify(lockoutData));
  }

  /**
   * 获取锁定剩余时间
   */
  getLockoutRemainingTime() {
    const lockoutData = localStorage.getItem('login_lockout');
    if (!lockoutData) return 0;

    const { timestamp } = JSON.parse(lockoutData);
    const elapsed = Date.now() - timestamp;
    const remaining = this.lockoutTime - elapsed;
    
    return Math.max(0, remaining);
  }

  /**
   * 重置表单
   */
  reset() {
    if (this.form) {
      this.form.reset();
    }
    
    // 清除所有错误状态
    this.clearFieldError('email');
    this.clearFieldError('password');
    this.hideFormError();

    // 重置密码可见性
    this.passwordInput.type = 'password';
    const icon = this.togglePasswordBtn.querySelector('i');
    icon.className = 'fa fa-eye';
    
    // 重置登录尝试次数
    this.loginAttempts = 0;
    localStorage.removeItem('login_lockout');
    
    // 更新表单状态
    this.updateFormState();
  }

  /**
   * 获取表单数据
   */
  getFormData() {
    return {
      email: this.emailInput.value.trim(),
      password: this.passwordInput.value,
      rememberMe: this.rememberMeCheckbox.checked
    };
  }

  /**
   * 设置表单数据
   */
  setFormData(data) {
    if (data.email) this.emailInput.value = data.email;
    if (data.password) this.passwordInput.value = data.password;
    if (data.rememberMe !== undefined) this.rememberMeCheckbox.checked = data.rememberMe;
    
    this.updateFormState();
  }
}

// 页面加载完成后初始化登录组件
document.addEventListener('DOMContentLoaded', () => {
  window.loginComponent = new LoginComponent();
});